package com.cf.dao.impl;
import com.cf.dao.db.BaseDao;
import com.cf.dao.entity.User;
import com.cf.dao.UserDao;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import static java.sql.DriverManager.getConnection;

public class UserDaoImpl extends BaseDao implements UserDao {
    //根据账号密码查询用户
    @Override
    public User selectUserByAccountAndPwd(String account, String password) throws SQLException {
        QueryRunner qr = new QueryRunner(getDataSource());
        String sql = "SELECT * FROM user WHERE account = ? AND password = ?";
        try (Connection conn = getDataSource().getConnection()) {
            return qr.query(conn, sql, new BeanHandler<>(User.class), account, password);
        }
    }
    //注册用户
    @Override
    public void insertUser(User user) throws SQLException {
        user.setAvatar("static/img/57813046.jpg");
        user.setAge(null);
        user.setSexy("未填写");
        user.setCommentall(0);
        user.setRoot(1);
        user.setState(1);
        user.setName("新用户");
        String sql = "INSERT INTO user(account, password, sexy, age, phone, avatar,email,commentall,root,state,name) VALUES(?, ?, ?, ?, ?, ?,?,?,?,?,?)";
        QueryRunner qr = new QueryRunner();
        try (Connection conn = getDataSource().getConnection()) {
            qr.update(conn, sql, user.getAccount(), user.getPassword(), user.getSexy(), user.getAge(), user.getPhone(), user.getAvatar(),user.getEmail(),user.getCommentall(),user.getRoot(),user.getState(),user.getName());
        }
    }
    //根据账号查询用户
    @Override
    public User selectUserByAccount(String account) throws SQLException {
        QueryRunner qr = new QueryRunner(getDataSource());
        String sql = "SELECT * FROM user WHERE account = ?";
        try (Connection conn = getDataSource().getConnection()) {  // 使用 BaseDao 获取连接
            return qr.query(conn, sql, new BeanHandler<>(User.class), account);  // 查询并返回用户
        }
    }
    //根据id更新用户信息
    @Override
    public boolean updateUserProfile(int userId, String name, int age, String sexy,String password) throws SQLException {
        String sql = "UPDATE user SET name = ?, age = ?,  sexy = ?, password = ? WHERE id = ?";
        QueryRunner qr = new QueryRunner(getDataSource());
        try (Connection conn = getDataSource().getConnection()) {
            return qr.update(conn, sql, name, age,  sexy,password, userId) > 0;
        }
    }
    @Override
    public boolean updateUserProfile(int userId, String name,int age,String sexy) throws SQLException {
        String sql = "UPDATE user SET name= ?,age=? WHERE id = ?";
        QueryRunner qr = new QueryRunner(getDataSource());
        try (Connection conn = getDataSource().getConnection()) {
            return qr.update(conn, sql, name,age, userId) > 0;
        }
    }
    //查询用户byId
    @Override
    public User selectUserById(int userId) throws SQLException {
        QueryRunner qr = new QueryRunner(getDataSource());
        String sql = "SELECT * FROM user WHERE id=?";
        try (Connection conn = getDataSource().getConnection()) {
            return qr.query(conn, sql, new BeanHandler<>(User.class),userId);
        }
    }
    //查询邮箱（查重）
    @Override
    public boolean selectUserByEmail(String email) throws SQLException {
        QueryRunner qr = new QueryRunner(getDataSource());
        String sql = "SELECT email FROM user WHERE email=?";
        try {
            // 只查询 email 字段来检查邮箱是否存在
            String result = qr.query(sql, new ScalarHandler<>(), email);
            return result != null;  // 如果查询返回的结果非空，表示邮箱已存在
        } catch (SQLException e) {
            throw new RuntimeException("查询邮箱失败", e);
        }
    }

    @Override
    public boolean saveImageUrlToDatabase(String imageUrl, int userId) {
        // 你需要在数据库中插入图片的 URL
        String sql = "UPDATE user SET avatar = ? WHERE id = ?";
        try (Connection conn = getDataSource().getConnection()) {
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setString(1, imageUrl);
                ps.setInt(2, userId); // 设置用户 ID
                return ps.executeUpdate() > 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

}